import {Component, ViewEncapsulation, ViewChild} from '@angular/core';
import {FormBuilder} from '@angular/forms';
import {IdeaService} from '../../services/app.idea';
import {Router}  from '@angular/router';
import {AuthenticationHelper} from '../../app.authentication';
import {BaThemeSpinner}  from '../../theme/services';
import {Utility} from '../../services/app.utility';
//import './editidea.loader.ts';
import {CKEditorComponent} from 'ng2-ckeditor';
import {Modal} from 'ngx-modal';
import {UserService} from '../../services/app.user';
declare let toastr:any;
declare let $:any;
declare let Treant:any;

@Component({
    selector: 'Editidea',
    encapsulation: ViewEncapsulation.None,
    template: './editidea.html',
    styles: ['./editidea.scss'],
    providers: [IdeaService]
})

export class Editidea {
    @ViewChild('citationTree')
    private citationTreeModal:Modal;
    @ViewChild('ckEditor')
    private ckEditor:CKEditorComponent;
    public title:any;
    public Content:any;
    public citation:any = {};
    public maxTag:Boolean;
    public tags:any = [];
    public id:any;
    public checkSubmit:boolean;
    public postTitle:string = null;
    public postDescription:string = null;
    public versioning:boolean;
    private cloudContentSuggestion:any;
    public cloudContentSuggestionWords:any;
    public citationArray1:any;

    public config = {
        uiColor: '#F0F3F4'
    };

    constructor(private fb:FormBuilder, private ideaService:IdeaService, private userService:UserService, private router:Router, private authentication:AuthenticationHelper, private spinner:BaThemeSpinner, private utility:Utility) {
        this.maxTag = false;
        this.citation.count = '';
        this.citation.name = '';
        this.citation.date = '';
        this.versioning = false;
        this.checkSubmit = true;
        this.cloudContentSuggestion = [];
        this.cloudContentSuggestionWords = [];
        this.citationArray1 = [];

        if (this.utility.editideas.id) {
            this.setEditIdea();
        } else {
            this.router.navigate(['listidea']);
        }

        // function for get user info
        this.userService.getuserInfo().subscribe(
            data => this.userInfoSuccess(data),
            error => this.userInfoFail(error)
        );
    }

    // function call user info failed
    public  userInfoFail(err) {

    }

    // Function call for set data into ckeditor
    public setEditIdea():void {
        this.id = this.utility.editideas.id;
        this.title = this.utility.editideas.title;
        this.Content = this.utility.editideas.content;
        this.tags = this.utility.editideas.tags;
        setTimeout(() => {
            this.putKeywords();
        }, 1000);
    }

    // Function for edit idea data
    public editIdea(id, title, content, tags):void {
        this.spinner.showProgress();
        for (let i = 0; i < this.cloudContentSuggestionWords.length; i++) {
            content = content.split(this.cloudContentSuggestionWords[i]).join('<span class="keywordColor">' + this.cloudContentSuggestionWords[i] + '</span>');
            this.citationArray1.push(this.cloudContentSuggestionWords[i]);
        }

        if (id) {
            this.spinner.showProgress();
            let data = {
                ideaId: id,
                title: title,
                content: content,
                tags: tags,
                citationArray: this.citationArray1,
                citation: {
                    'showCount': this.citation.count,
                    'name': this.citation.name,
                    'updatedAt': this.citation.date
                },
                cloudContent: this.ckEditor.instance.editable().getText(),
            };
            this.checkSubmit = false;
            this.ideaService.editIdea(data).subscribe(
                data => this.editIdeaSucessfully(),
                error => this.editIdeaFail(error));
        }
    }

    // function call when edit idea success
    private editIdeaSucessfully() {
        this.spinner.hideProgress();
        toastr.success('Edit Idea Successfully');
        while (this.tags.length)
            this.tags.pop();
        this.title = '';
        this.Content = '';
        let input = {
            'target': 'EditIdea form filled',
            'value': 'EditIdea',
            'action': 'keystroke'
        };
        this.setUserLogs(input);
        this.router.navigate(['listidea']);
    }

    // function call when edit idea fail
    private editIdeaFail(error) {
        this.spinner.hideProgress();
        toastr.error(error.error_message);
    }

    // function for check tags count
    public isMaxtagReached() {
        if (this.tags.length > 5) {
            this.tags.pop();
            this.maxTag = true;
        }
        else {
            this.maxTag = false;
        }
    }

    // Function for get keywords from NLP
    public getUniqueKeywords(keyword) {
        let newKeywords = [];
        for (let i = 0; i < keyword.length; i++) {
            if (newKeywords.indexOf(keyword[i].content) < 0) {
                newKeywords.push(keyword[i].content);
            }
        }
        return newKeywords;
    }

    // Call when load ckeditor
    private onReady($event) {
        this.ckEditor.instance.on('key', (event) => {
          let input = event.data.domEvent.$.code;
          this.onKeyPressUserForCkeditor(input);
            setTimeout(() => {

                if (event.data.keyCode === 32 && this.versioning) {
                    let currentSentence = this.ckEditor.instance.editable().getText().split(/[?!.]/g);
                    if (currentSentence[currentSentence.length - 1].toString().trim().length > 0) {

                        let firstContent = currentSentence[currentSentence.length - 1].toString().trim();
                        let res = firstContent.split(" ");
                        let output = res.length - 1;

                        let cloudData = {
                            content: res[output],
                            wholeContent: this.ckEditor.instance.editable().getText()
                        };

                        this.ideaService.getReproducibleCitableKeywordsSuggestion(cloudData).subscribe(
                            data => this.autoSuggestionSucces(data),
                            error => {
                            });
                    }
                } else if (this.ckEditor.instance.editable().getText().trim() == '') {
                    this.cloudContentSuggestion = [];
                    this.cloudContentSuggestionWords = [];
                } else {
                    if ((event.data.keyCode == 46) || (event.data.keyCode == 1114198) ||
                        (event.data.keyCode == 8) || (event.data.keyCode == 1114202)
                        || (event.data.keyCode == 1114200)) {
                        this.putKeywords();
                    }
                }
            }, 100);
        });
    }

    // Call when auto suggestion success
    public autoSuggestionSucces(result) {
        this.cloudContentSuggestion = result.autoComplete;
        this.cloudContentSuggestionWords = this.getUniqueKeywords(result.sentence);
    }

    // Function for call API citation word from NLP
    public fillKeywords(id, title, Content, tags) {
        this.spinner.showProgress();
        let cloudData = {
            content: this.ckEditor.instance.editable().getText(),
            wholeContent: this.ckEditor.instance.editable().getText()
        };
        this.ideaService.getReproducibleCitableKeywordsSuggestion(cloudData).subscribe(
            data => this.fillKeywordsSuccess(data, title, Content, id, tags),
            error => {
            });
    }

    // Function for fill keywords success
    private fillKeywordsSuccess(result, title, Content, id, tags) {
        this.spinner.showProgress();
        if (result.showCount > 0) {
            this.citation.count = result.showCount;
            this.citation.name = result.sentence[0].name;
            this.citation.date = this.utility.getFormattedDate(result.sentence[0].updatedAt);
        }
        this.editIdea(id, title, Content, tags);
    }

    // API call for find cited word
    private putKeywords() {
        setTimeout(() => {
            let cloudData = {
                content: '',
                wholeContent: this.ckEditor.instance.editable().getText()
            };
            this.ideaService.getReproducibleCitableKeywordsSuggestion(cloudData).subscribe(
                data => this.putKeywordsSuccess(data),
                error => {
                });
        }, 200);
    }

    // After get suggestion pass to view.
    public putKeywordsSuccess(result) {
        this.cloudContentSuggestionWords = this.getUniqueKeywords(result.sentence);
        this.cloudContentSuggestion = [];
    }

    // Function for put suggestion
    private putSuggestion(suggest) {
        let ckeditorLength = this.Content.length;
        let chkStr = '';
        let currentSentence = this.ckEditor.instance.editable().getText().split(/[?!.]/g);
        let newContent = '';
        let curPos = 0;
        let extractStr = currentSentence[currentSentence.length - 1];
        while (chkStr !== extractStr && ckeditorLength >= 0) {
            curPos = ckeditorLength - extractStr.length - 1;
            chkStr = this.Content.substring(curPos, curPos + extractStr.length);
            --ckeditorLength;
        }

        let inputOfCkeditor = this.Content.substring(curPos + extractStr.length, this.Content.length - 1);
        let x = inputOfCkeditor.substr(0, inputOfCkeditor.lastIndexOf('.'));
        let z = x + '.';


        newContent = this.Content.substring(0, curPos) + z + suggest;

        this.ckEditor.writeValue(newContent);
        this.cloudContentSuggestion = [];
        this.putKeywords();
    }

    // Function for pass tree data to other function
    public getTreeStructure(citedWords) {
        this.getTreeData(citedWords);
    }

    // API call for get citation tree data fro server
    private getTreeData(data):void {
        let inputData = {content: [data]};
        this.spinner.showProgress();
        this.ideaService.getCitationTreeData(inputData).subscribe(
            data => this.generateTree(data),
            error => {
            });
    }

    // functiona for generate citation tree
    private generateTree(data) {
        this.citationTreeModal.open();
        setTimeout(() => {
            let chartConfig = {
                chart: {
                    container: '#tree-simple',
                    scrollbar: 'fancy',
                    siblingSeparation: 20,
                    subTeeSeparation: 60,
                    connectors: {
                        type: 'step'
                    },
                    node: {
                        HTMLclass: 'nodeExample1'
                    }
                },
                nodeStructure: data

            };
            let chart = new Treant(chartConfig);
        }, 1000);
        this.spinner.hideProgress();

    }

    // defined cloud content array.
    ngAfterViewinit() {
        this.cloudContentSuggestionWords = [];
    }

    // Function for show data as per version name
    public userInfoSuccess(data) {
        console.log("edit idea");
        if (data.version === 'Version_1') {
            this.versioning = false;
        } else if (data.version === 'Version_2') {
            this.versioning = false;
        } else if (data.version === 'Version_3') {
            this.versioning = false;
        } else if (data.version === 'Version_5') {
            this.versioning = false;
        } else {
            this.versioning = true;
        }
    }


    // Function call for set user log data using API
    public setUserLogs(input) {
        this.userService.setUserLogs(input).subscribe();
    }

  // User log for keystroke event for title
  public onKeyPressUser(event) {

    let input = {
      'target': 'HTMLInputElement : ' + event.code + '  Edit idea title',
      'action': 'keystroke'
    };
    // API call for send user log data
    this.userService.setUserLogs(input).subscribe();
  }

  // User log for keystroke event for title
  public onKeyPressUserForCkeditor(event) {

    let input = {
      'target': 'HTMLInputElement : ' + event + '  Edit idea description',
      'action': 'keystroke'
    };
    // API call for send user log data
    this.userService.setUserLogs(input).subscribe();
  }
}
